<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button icon="el-icon-plus" type="primary" @click="handleAdd">添加</el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleAnyDelete">删除</el-button>
        <el-button v-popover:popoverAll type="primary" icon="el-icon-upload2">导出Excel</el-button>
        <el-button v-popover:popoverPart type="primary" icon="el-icon-upload2">导出选中行</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel>
        <el-cascader
          v-if="user.level <= 1"
          :options="townToVillage"
          :props="townToVillProp"
          placeholder="地区筛选"
          change-on-select
          clearable
          @change="townToVillageChange"
        />
        <el-select
          v-if="user.level == 1 && queryForm.subsidyType"
          v-model="queryForm.subsidy"
          multiple
          placeholder="补助项筛选"
          clearable
          @change="subsidyChange"
        >
          <el-option
            v-for="subsidy in subsidyAtt"
            :key="subsidy.id"
            :label="subsidy.name"
            :value="subsidy.id"
          />
        </el-select>
        <el-cascader
          v-if="user.level == 2"
          :options="townToVillage"
          :props="townToVillProp"
          placeholder="地区筛选"
          change-on-select
          clearable
          @change="villageToTypeChange"
        />
        <el-select
          v-if="user.level == 3"
          v-model="queryForm.subsidyType"
          multiple
          placeholder="类型筛选"
          clearable
          @change="typeChange"
        >
          <el-option
            v-for="village in queryVillageAtt"
            :key="village.id"
            :label="village.name"
            :value="village.id"
          />
        </el-select>
        <el-form ref="form" :model="queryForm" :inline="true" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="queryForm.keyword" placeholder="查询内容或字段" clearable />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              native-type="submit"
              @click="handleQuery"
            >查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="95">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="village.name" label="所属村" />
      <el-table-column prop="name" label="补助对象" />

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline label-width="120px" class="demo-table-expand">
            <el-form-item label="补助项名字">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item :label="props.row.personal ? '补助个人姓名': '补助户'">
              <span>{{ props.row.name }}</span>
            </el-form-item>

            <el-form-item label="所属村">
              <span>{{ props.row.village.name }}</span>
            </el-form-item>
            <el-form-item label="所属组">
              <span>{{ props.row.group && props.row.group.name }}</span>
            </el-form-item>
            <el-form-item label="所属街道">
              <span>{{ props.row.village.town.name }}</span>
            </el-form-item>

            <template v-if="props.row.personal">
              <el-form-item label="性别">
                <span>{{ props.row.sex | getSex }}</span>
              </el-form-item>
              <el-form-item label="民族">
                <span>{{ props.row.nation | getNation }}</span>
              </el-form-item>
              <el-form-item label="手机号">
                <span>{{ props.row.phone }}</span>
              </el-form-item>
              <el-form-item label="身份证号">
                <span>{{ props.row.identityNumber }}</span>
              </el-form-item>
            </template>

            <el-form-item label="家庭地址">
              <span>{{ props.row.address }}</span>
            </el-form-item>
            <el-form-item label="申请时间">
              <span>{{ props.row.applicationTime }}</span>
            </el-form-item>
            <el-form-item label="补助原因">
              <span>{{ props.row.cause }}</span>
            </el-form-item>
            <el-form-item label="备注信息">
              <span>{{ props.row.remarks }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column prop="subsidyType.name" label="补助类型" />
      <el-table-column prop="subsidy.name" label="补助项" sortable="custom" />
      <el-table-column prop="applicationTime" label="申请时间" sortable="custom" />
      <el-table-column prop="remarks" label="备注信息" />
      <el-table-column label="操作" width="180px" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row class="d-flex jc-between ai-bottom">
      <el-col :span="12" class="grid-content d-flex jc-between ai-center" style="margin-top: 15px;">
        <el-button type="primary" @click="showUpload">
          上传
          <i class="el-icon-upload el-icon--right" />
        </el-button>
      </el-col>
      <el-col :span="12">
        <div class="grid-content">
          <el-pagination
            :background="background"
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 导出Excel -->
    <el-popover ref="popoverAll" placement="right" width="250" trigger="click">
      <vab-query-form>
        <vab-query-form-left-panel :span="24">
          <el-form label-position="right" :inline="false" size="mini" @submit.native.prevent>
            <el-form-item label="文件名">
              <el-input v-model="filename" placeholder="请输出要导出文件的名称" clearable />
            </el-form-item>
            <el-form-item label="文件类型">
              <el-select v-model="bookType">
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item"
                  :value="item"
                  clearable
                />
              </el-select>
            </el-form-item>
            <el-form-item label="自动列宽">
              <el-radio-group v-model="autoWidth">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="allHandleDownload">导出 Excel</el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
      </vab-query-form>
    </el-popover>
    <!-- 导出选中行 -->
    <el-popover ref="popoverPart" placement="right" width="250" trigger="click">
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form :inline="true" @submit.native.prevent>
            <el-form-item>
              <el-input v-model="filename" placeholder="请输出要导出文件的名称" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="partHandleDownload()">导出选中行</el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
      </vab-query-form>
    </el-popover>

    <table-edit ref="edit" @fetchData="fetchData" />

    <el-dialog
      v-if="complete"
      title="补助信息文件上传"
      :visible.sync="dialogFormUpload"
      :fullscreen="true"
      :lock-scroll="true"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="closeUpload"
    >
      <upload-table @close="closeUpload" />
    </el-dialog>
  </div>
</template>

<script>
//手动添加
import UploadTable from "./UploadTable.vue";
import { mapGetters } from "vuex";
import TableEdit from "@/views/my-views/Info/subsidy-info/TableEdit";
export default {
  name: "MyTable",
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  components: {
    TableEdit,
    UploadTable,
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      list: [],
      listLoading: false,
      layout: "total, sizes, prev, pager, next, jumper",
      total: 0,
      background: true,
      selectRows: "",
      elementLoadingText: "正在加载...",
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        town: "",
        village: "",
        keyword: "",
        subsidyType: [],
        subsidy: "",
      },

      // excle 导出
      filename: "补助信息",
      autoWidth: true,
      bookType: "xlsx",
      options: ["xlsx", "csv", "txt"],

      table: {},
      selectedData: {},
      sort: [],

      // 搜索
      townToVillProp: {
        value: "id",
        label: "name",
        children: "village",
      },
      townToVillage: [],
      queryVillageAtt: [],
      subsidyAtt: [],
      dialogFormUpload: false,

      complete: true,
    };
  },
  created() {
    this.init();
    this.fetchData();
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    tableSortChange(column) {
      // const imageList = [];
      // this.$refs.tableSort.tableData.forEach((item, index) => {
      //   imageList.push(item.img);
      // });
      console.log(column);
      if (column.order) {
        this.sort = [
          `${column.prop},${column.order == "descending" ? "DESC" : "ASC"}`,
        ];
      } else {
        this.sort = [];
      }
      this.fetchData();
    },
    setSelectRows(val) {
      this.selectRows = val;
      this.selectedData = this.transformData(val);
    },
    handleAdd() {
      this.$refs["edit"].showEdit();
    },
    handleEdit(row) {
      this.$refs["edit"].showEdit(row);
    },
    handleDelete(id) {
      this.$baseConfirm("你确定要删除当前项吗", null, async () => {
        await this.delete(id);
      });
    },
    handleAnyDelete() {
      if (this.selectRows.length > 0) {
        const att = JSON.parse(JSON.stringify(this.selectRows));
        this.$baseConfirm("你确定要删除选中项吗", null, () => {
          att.forEach(async (item) => {
            await this.delete(item.id);
          });
        });
      } else {
        this.$baseMessage("未选中任何行", "error");
      }
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    getQuery() {
      let query = JSON.parse(JSON.stringify(this.queryForm));
      //镇村筛选
      let fields = "";
      let s = {
        $or: [
          {
            "village.name": {
              $cont: query.keyword,
            },
          },
          {
            "subsidy.name": {
              $cont: query.keyword,
            },
          },
          {
            "subsidy.amount": {
              $cont: query.keyword,
            },
          },
          {
            "subsidy.items": {
              $cont: query.keyword,
            },
          },
          {
            "subsidy.standards": {
              $cont: query.keyword,
            },
          },
          {
            "subsidy.nationalPolicy": {
              $cont: query.keyword,
            },
          },
          {
            "subsidy.implementationPolicy": {
              $cont: query.keyword,
            },
          },
          {
            "subsidyType.name": {
              $cont: query.keyword,
            },
          },
          {
            name: {
              $cont: query.keyword,
            },
          },
          {
            phone: {
              $cont: query.keyword,
            },
          },
          {
            identityNumber: {
              $cont: query.keyword,
            },
          },
          {
            address: {
              $cont: query.keyword,
            },
          },
        ],
        init() {
          if (query.village) {
            if (Array.isArray(query.village) && query.village.length > 0) {
              this["village.id"] = {
                $in: query.village,
              };
            } else if (!Array.isArray(query.village)) {
              this["village.id"] = {
                $eq: query.village,
              };
            }
          }
          if (query.town) {
            this["village.town.id"] = {
              $eq: query.town,
            };
          }
          if (query.subsidyType.length > 0) {
            this["subsidyType.id"] = {
              $in: query.subsidyType,
            };
          }
          // if(query.subsidy) {
          //   this['subsidy.id'] = {
          //     "$eq": query.subsidy
          //   }
          // }
          return this;
        },
      };
      console.log(query);
      let filterInfo =
        query.village !== "" &&
        query.village &&
        (Array.isArray(query.village) ? query.village.length > 0 : true)
          ? `filter=village.town.id||$eq||${
              query.town
            }&filter=village.id||$in||${query.village.toString()}`
          : query.town !== "" && query.town
          ? `filter=village.town.id||$eq||${query.town}`
          : "";
      let or = "";
      let sort = `${this.sort
        .map((item) => `sort=${item}`)
        .join("&")}&sort=createdAt,DESC`;
      let join = `join=village&join=village.town&join=group&join=subsidy&join=subsidyType`;
      let pageInfo = `limit=${query.pageSize}&page=${query.pageNo}`;

      //列排序 列名 排序规则 ASC(递增),DESC(递降)
      //粗略搜索
      // let search = ''
      return `fields=${fields}&s=${JSON.stringify(
        s.init()
      )}&${filterInfo}&or=${or}&${sort}&${join}&${pageInfo}`;
    },
    async fetchData() {
      this.listLoading = true;
      let res = await this.$http.get("subsidy-info" + `?${this.getQuery()}`);
      this.list = res.data.data;
      this.total = res.data.total;
      this.listLoading = false;
      this.table = this.transformData(this.list);
      console.log(this.table);
    },

    async delete(id) {
      const res = await this.$http.delete(`subsidy-info/${id}`);
      if (res.status == 200) {
        this.$baseMessage("删除成功", "success");
        this.fetchData();
      } else {
        this.$baseMessage("删除失败", "error");
      }
    },

    transformData(objectData) {
      let header = [];
      let data = [];
      if (objectData.length > 0) {
        for (const key in objectData[0]) {
          header.push(key);
        }
        objectData.forEach((item) => {
          let att = [];
          header.forEach((key) => att.push(item[key]));
          data.push(att);
        });
      }
      return {
        header,
        data,
      };
    },

    getImportConfig() {
      console.log(this);
      return {
        allFiles: [
          "subsidy",
          "personal",
          "village",
          "group",
          "name",
          "sex",
          "nation",
          "phone",
          "identityNumber",
          "address",
          "cause",
          "remarks",
          "applicationTime",
        ],
        exclude: ["id", "subsidyType"],
        village: {
          index: 1,
          alias: "所属村",
          map: (village) => village && village.name,
        },
        group: {
          index: 2,
          alias: "所属组",
          // map: () => {}
          map: (group) => group && group.name,
        },
        subsidy: {
          index: 4,
          alias: "补助项",
          map: (subsidy) => subsidy && subsidy.name,
        },
        personal: {
          index: 5,
          alias: "是否是补助个人",
          map: (personal) => (personal ? "是" : "否"),
        },
        name: {
          index: 5,
          alias: "补助对象或补助户姓名",
          // map: () => {}
        },
        sex: {
          index: 6,
          alias: "补助对象性别(补助户可以忽略)",
          map: (sex) => this.$options.filters["getSex"](sex),
        },
        nation: {
          index: 7,
          alias: "补助对象民族(补助户可以忽略)",
          map: (nation) =>
            nation ? this.$options.filters["getNation"](nation) : nation,
        },
        phone: {
          index: 8,
          alias: "电话",
          // map: () => {}
        },
        identityNumber: {
          index: 9,
          alias: "身份证号(补助户可以忽略)",
          // map: () => {}
        },
        address: {
          index: 10,
          alias: "家庭地址",
          // map: () => {}
        },
        cause: {
          index: 11,
          alias: "补助原因",
          // map: () => {}
        },
        remarks: {
          index: 12,
          alias: "备注",
          // map: () => {}
        },
        applicationTime: {
          index: 13,
          alias: "申请时间",
          // map: () => {}
        },
        createdAt: {
          index: 14,
          alias: "创建时间",
          map: (str) => this.XEUtils.toDateString(str),
        },
      };
    },
    //excel 导出
    allHandleDownload() {
      import("@/vendor/ExportExcel").then((excel) => {
        const { header, data } = this.importAndExportConfig(
          this.table,
          this.getImportConfig()
        );
        excel.export_json_to_excel({
          header,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType,
        });
      });
    },
    partHandleDownload() {
      if (
        Array.isArray(this.selectedData.data) &&
        this.selectedData.data.length > 0
      ) {
        import("@/vendor/ExportExcel").then((excel) => {
          const { header, data } = this.importAndExportConfig(
            this.table,
            this.getImportConfig()
          );
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
        });
      } else {
        this.$baseMessage("没有选择数据 默认导出表头", "warning");

        import("@/vendor/ExportExcel").then((excel) => {
          const { header, data } = this.importAndExportConfig(
            this.getImportConfig()
          );

          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
        });
      }
    },

    async init() {
      this.setQuery();
      if (this.user.level <= 1) {
        const res = await this.$http.get(
          `town?join=village&join=village.subsidyType&join=village.subsidyType.subsidy`
        );
        let children = "village";
        res.data.forEach((town) => {
          town.village.forEach((village) => {
            village[children] = village.subsidyType;
            village.subsidyType.forEach((subsidyType) => {
              subsidyType[children] = subsidyType.subsidy;
            });
          });
        });
        this.townToVillage = res.data;
        console.log(this.townToVillage);
      } else if (this.user.level == 2) {
        const res = await this.$http.get(
          `town/${this.user.town.id}?join=village&join=village.subsidyType&join=village.subsidyType.subsidy`
        );
        let children = "village";
        res.data.village.forEach((village) => {
          village[children] = village.subsidyType;
          village.subsidyType.forEach((subsidyType) => {
            subsidyType[children] = subsidyType.subsidy;
          });
        });
        this.townToVillage = res.data.village;
        console.log(this.townToVillage);
      } else if (this.user.level == 3) {
        const res = await this.$http.get(
          `village/${this.user.village.id}?join=subsidyType`
        );
        this.queryVillageAtt = res.data.subsidyType;
      }
    },
    setQuery() {
      if (this.user.level == 2) {
        this.queryForm.town = this.user.town.id;
        console.log(this.queryForm.town);
      } else if (this.user.level == 3) {
        this.queryForm.town = this.user.town.id;
        this.queryForm.village = this.user.village.id;
      }
    },
    async townToVillageChange(att) {
      this.queryForm.town = att[0];
      this.queryForm.village = att[1] || "";
      this.queryForm.subsidyType = att[2] || "";
      // console.log(this.queryForm.subsidyType, `--------------`)
      // if(this.queryForm.subsidyType) {
      //   const res = await this.$http.get(`subsidyType/${this.queryForm.subsidyType}`)
      //   this.subsidyAtt = res.data.subsidy
      // }
      // this.queryForm.subsidy = att[3] || ""
      this.fetchData();
    },
    villageToTypeChange(att) {
      this.queryForm.village = att[0];
      this.queryForm.subsidyType = att[1] || "";
      this.fetchData();
    },
    typeChange(att) {
      this.fetchData();
    },
    subsidyChange(att) {
      this.fetchData();
    },

    //文件上传
    showUpload() {
      this.complete = true;
      this.dialogFormUpload = true;
    },
    closeUpload(upload) {
      this.dialogFormUpload = false;
      if (upload) {
        this.complete = false;
        this.fetchData();
      }
    },
  },
};
</script>

<style lang="scss">
.demo-table-expand {
  font-size: 0;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  flex: 0 0 25%;
  text-align: left;
}

//flex
.d-flex {
  display: flex !important;
}
.flex-column {
  flex-direction: column;
}

$flex-jc: (
  start: start,
  end: end,
  center: center,
  between: space-between,
  around: space-around,
);

//.jc-
@each $key, $value in ($flex-jc) {
  .jc-#{$key} {
    justify-content: $value !important;
  }
}

$flex-ai: (
  start: start,
  end: end,
  center: center,
  stretch: stretch,
);

//.ai-
@each $key, $value in ($flex-jc) {
  .ai-#{$key} {
    align-items: $value !important;
  }
}
</style>